//
//  SQLiteManager.m
//  oc数据库demo
//
//  Created by whong7 on 16/9/26.
//  Copyright © 2016年 whong7. All rights reserved.
//

#import "SQLiteManager.h"



static SQLiteManager *manager = nil;

@implementation SQLiteManager

+ (SQLiteManager *)sharedSQLiteManager{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[SQLiteManager alloc] init];
    });
    return manager;
}
- (instancetype)init {
    if (self = [super init]) {
        
        // 1. 创建数据库
        [self createDataBase];
        
        // 2. 创建表格
        [self createTable];
        
    }
    return self;
}


//创建数据库
- (void)createDataBase{
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES)firstObject];
    NSString *filePath = [doc stringByAppendingPathComponent:@"contacts.sqlite"];
    NSLog(@"路径：%@",filePath);
    //创建数据库
    self.db = [FMDatabase databaseWithPath:filePath];
}
//创建表
- (void)createTable{
    if ([self.db open]) {
        BOOL result = [self.db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_contact (goods_id integer , name text , count integer ,img text,partner_price real);"];
        if (result) {
            NSLog(@"创建成功");
        }else{
            NSLog(@"创建失败");
        }[self.db close];
    }else{
        NSLog(@"数据库打开失败");
    }
}
//插入操作
- (void)insertContact:(CNGoodsModel *)contact{
    if ([self.db open]) {
        BOOL result = [self.db executeUpdate:@"INSERT INTO t_contact (goods_id, name,count,img,partner_price) VALUES (?,?,?,?,?);",[NSNumber numberWithInt:contact.goods_id] , contact.name,@1,contact.img,[NSNumber numberWithFloat:contact.partner_price]];
        if (result) {
            NSLog(@"创建成功");
        }else{
            NSLog(@"创建失败");
        }
        [self.db close];
    }else{
        NSLog(@"数据库打开失败");
    }
}
//删除
- (void)deleteContact:(CNGoodsModel *)contact{
    if ([self.db open]) {
        BOOL result = [self.db executeUpdate:@"delete from t_contact where count = 0"];
        if (result) {
            NSLog(@"创建成功");
        }else{
            NSLog(@"创建失败");
        }
        [self.db close];
    }else{
        NSLog(@"数据库打开失败");
    }
}

//修改数据
- (void)updateContact:(CNGoodsModel *)contact With:(int)addCount
{
    if ([self.db open]) {
        BOOL result = [self.db executeUpdate:@"UPDATE t_contact SET count = ? WHERE goods_id = ?",[NSNumber numberWithInt:(contact.count+addCount)],[NSNumber numberWithInt:contact.goods_id]];
        if (result) {
            NSLog(@"修改成功");
            //修改成功后清除count为0的数据
            [self deleteContact:contact];
        }
        else
        {
            NSLog(@"修改失败");
        } [self.db close];
    }else{
        NSLog(@"数据库打开失败");
    }
}

//查询
- (NSArray *)queryContact{
    NSMutableArray *arr = [NSMutableArray array];
    if ([self.db open]) {
        FMResultSet *set = [self.db executeQuery:@"SELECT * FROM t_contact"];
        while ([set next]) {
            NSInteger goods_id = [set intForColumn:@"goods_id"];
            float partner_price = [set intForColumn:@"partner_price"];
            NSString *img = [set stringForColumn:@"img"];
            NSInteger count = [set intForColumn:@"count"];
            NSString *name = [set stringForColumn:@"name"];
            CNGoodsModel *contact = [[CNGoodsModel alloc]initWithName:name count:count img:img partner_price:partner_price goods_id:goods_id];
            [arr addObject:contact];
        }
    }
    return arr;
}

// 清除表
- (void) eraseTable
{
    if ([self.db open]) {
        BOOL result = [self.db executeUpdate:@"DELETE FROM t_contact"];
        if (result) {
             NSLog(@"清空数据库");
            //发送通知
            [[NSNotificationCenter defaultCenter] postNotificationName:@"购物车" object:nil userInfo:@{@"totalCount":[NSNumber numberWithInt:0]}];
        }
        else
        {
            NSLog(@"修改失败");
        } [self.db close];
    }else{
        NSLog(@"数据库打开失败");
    }

}


#pragma mark - 1.进行数据查询
//  no:插入数据
//  yes:已有数据count+1
-(void)charu:(NSObject *)model With:(int)addCount
{
    //将传入的模型进行 归一转换
    NSDictionary *dict = [NSDictionary DictOfModel:model];
    CNGoodsModel *goodModel = [CNGoodsModel yy_modelWithJSON:dict];
    
    //取到遍历出来的模型
    CNGoodsModel *fillModel = [self beInclude:goodModel With:addCount];
    
    //如果遍历出来的模型存在，就去修改对应的count值
    if (fillModel) {
         //修改数据，需要传输的模型，是从数据里面遍历出来的数组模型
        [self updateContact:fillModel With:addCount];
    }
    //如果遍历出来的模型不存在，就去插入该模型
    else
    {
        //如果没有数据，进行添加添加操作 才会进行插入
        if (addCount == 1) {
            [self insertContact:goodModel];
        }
        
    }

}

/**
 判断是否包含该模型

 @param model 点击的cell模型

 @return 有的话返回模型 没有的话返回空
 */
- (CNGoodsModel *)beInclude:(CNGoodsModel *)model With:(int)addCount
{
    NSArray *array = [self queryContact];
    
    CNGoodsModel *tureValue ;
    int totalCount = 0;
    for (CNGoodsModel *value in array) {
        if (value.goods_id == model.goods_id) {
            tureValue = value;
        }
        totalCount += value.count;
    }
    //发送通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"购物车" object:nil userInfo:@{@"totalCount":[NSNumber numberWithInt:(totalCount + addCount)]}];
    
    if (tureValue) {
        return tureValue;
    }
    return nil;
}

#pragma mark - 2.进行数据提取
-(NSArray *)getValueWith:(NSArray *)modelArray
{
    for (NSObject *model in modelArray) {
        //将传入的模型进行 归一转换
        NSDictionary *dict = [NSDictionary DictOfModel:model];
        CNGoodsModel *goodModel = [CNGoodsModel yy_modelWithJSON:dict];
        
        //取到遍历出来的模型
        CNGoodsModel *fillModel = [self beInclude:goodModel With:0];
        
        //如果遍历出来的模型存在，就去修改对应的count值
        if (fillModel) {
            [model setValue:[NSNumber numberWithInt:fillModel.count] forKey:@"count"];
        }
        else
        {
        //如果遍历出来的模型不存在，不去修改
            [model setValue:[NSNumber numberWithInt:0] forKey:@"count"];
        }
        NSLog(@"%@",goodModel);

    }
    NSLog(@"%@",modelArray);
    return modelArray;
    
}

@end


